const { Sequelize,Op } = require('sequelize');
const obj = {}
const {DBNAME,DBUSER,DBPWD,DBHOST} = require('../config')
const { findFiles } = require('../tools')
const path = require('path')

const db = new Sequelize(DBNAME,DBUSER,DBPWD,{
    host:DBHOST,
    dialect:'mysql',
    timezone:"+08:00"
})
obj.db = db;

db.authenticate().then(success=>{
    console.log("数据库连接成功");
}).catch(err=>{
    console.log("数据库连接失败",err);
})

const files = findFiles('./models');

files.forEach(fileName=>{
    let tbName = fileName.replace('.js','').toLowerCase();
    let tbObj = require(path.join(__dirname,'../models',fileName));
    obj[tbName] = db.define(tbName,tbObj,{
        charset:"utf8"
    })
})

obj.sync = force=>db.sync({force});
obj.Op = Op
obj.Result = function(code,data,msg,result){
    this.code = code,
    this.data = data,
    this.msg = msg,
    this.result = result
}

// obj.sync(true).then(e=>{
//     console.log("数据库同步成功",e);
// }).catch(err=>{
//     console.log("数据库同步失败",err);
// })

module.exports = obj;